package com.sz.biz.csr.service.impl;

import com.sz.biz.csr.constants.CsrConstants;
import com.sz.biz.csr.entity.CsrAskBoardDetail;
import com.sz.biz.csr.entity.CsrAskBoardSchema;
import com.sz.biz.csr.dto.CsrAskBoardDetailDto;
import com.sz.biz.csr.dto.CsrAskBoardSchemaDto;
import com.sz.biz.csr.service.CsrAskBoardDetailService;
import com.sz.biz.csr.service.CsrAskBoardSchemaService;
import com.sz.biz.csr.service.CsrWorkOrderSchemaService;
import com.sz.biz.common.constants.ErrorCodes;
import com.sz.biz.common.constants.ModuleNames;
import com.sz.biz.common.customer.entity.CusUser;
import com.sz.biz.common.customer.service.CustomerUserService;
import com.sz.common.base.constants.AppDomain;
import com.sz.common.base.constants.UserActions;
import com.sz.common.base.dao.ParamData;
import com.sz.common.base.dto.QResultDto;
import com.sz.common.base.dto.QueryParams;
import com.sz.common.base.exception.Exceptions;
import com.sz.common.base.service.AbstractService;
import com.sz.common.base.utils.StringUtils;
import com.sz.common.core.service.PrincipalLogUtils;
import com.sz.common.core.service.PrincipalUtils;
import com.sz.common.core.system.dto.UserDto;
import com.sz.common.core.system.service.UserService;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by xutao on 17/5/12.
 */

@Service("CsrAskBoardSchemaService")
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class CsrAskBoardSchemaServiceImpl extends AbstractService implements CsrAskBoardSchemaService {

    @Autowired
    CustomerUserService customerUserService;

    @Autowired
    UserService userService;

    @Autowired
    CsrAskBoardDetailService csrBoardDetailService;

    @Autowired
    CsrWorkOrderSchemaService csrWorkOrderSchemaService;

    @Override
    public CsrAskBoardDetailDto save(CsrAskBoardSchema entry) {
        int resId = 0;
        if (entry != null) {
            entry.setRefCustomerId(PrincipalUtils.getAccountId());
            entry.setLastReplyId(PrincipalUtils.getAccountId());
            entry.setModeratorForReplyer(true);
            entry.setStatus(false);
            Map<String,String> serialNumber = generateSerialNumber();
            entry.setCode(serialNumber.get("dateString")+serialNumber.get("serialNumber"));
            entry.setSerialNumber(Integer.valueOf(serialNumber.get("serialNumber")));
            dao.save(getSqlName("insertSelective"), entry);
            CsrAskBoardDetail csrAskBoardDetail = new CsrAskBoardDetail();

            csrAskBoardDetail.setIsModerator(true);
            csrAskBoardDetail.setRefReplyerId(PrincipalUtils.getAccountId());
            csrAskBoardDetail.setMessageBody(entry.getContent());
            csrAskBoardDetail.setRefAskBoardId(entry.getId());
            CsrAskBoardDetailDto  csrAskBoardDetailDto =  csrBoardDetailService.save(csrAskBoardDetail);

            //保存操作日志
            Map<String, Object> dataBackup = new HashMap<>();
            dataBackup.put("ADD_CUSTOMERSERVICE_ASKBOARD_SCHEMA", entry);
            PrincipalLogUtils.addOperationLog(ModuleNames.CSR, ModuleNames.CSR_ASK_BOARD, UserActions.ADD, "新增客服问题单", dataBackup);
            return csrAskBoardDetailDto;
        }
        return null;
    }

    @Override
    public void batchDelete(List<Integer> ids) {

        if (ids != null && ids.size() > 0) {

            for (int i=0; i<ids.size(); i++) {

                CsrAskBoardSchema csrAskBoardSchema = (CsrAskBoardSchema)dao.findForObject(getSqlName("selectByPrimaryKey"), ids.get(i));

                if (csrAskBoardSchema != null) {

                    if (!csrAskBoardSchema.getStatus()) {

                        throw Exceptions.bizException(ErrorCodes.ERROR_CUSTOMER_SERVICE_ASKBOARD_DELETED);
                    }

                    Boolean isExist = csrWorkOrderSchemaService.isContainOddNumber(1, String.valueOf(csrAskBoardSchema.getId()));

                    if (isExist) {

                        throw Exceptions.bizException(ErrorCodes.ERROR_CUSTOMER_SERVICE_ASKBOARD_NOT_DELETED_WORKORDER);
                    }
                }
            }

            dao.update(getSqlName("logicDeleteByIds"), ids);
        }

        Map<String, Object> dataBackup = new HashMap<>();
        dataBackup.put("DELETE_CUSTOMERSERVICE_ASKBOARD_SCHEMA", ids);
        PrincipalLogUtils.addOperationLog(ModuleNames.CSR, ModuleNames.CSR_ASK_BOARD, UserActions.DELETE, "删除客服问题单", dataBackup);
    }

    @Override
    public QResultDto getAskBoardSchemaList(String q, int pageIndex, int pageSize, String sortName,
                                            boolean isAsc, String language, Date beginTime, Date endTime,
                                            int customerId, int status, String customerName) {

        List<CsrAskBoardSchemaDto> csrAskBoardSchemaDtoList = new ArrayList<CsrAskBoardSchemaDto>();

        QueryParams params = new QueryParams(pageSize, pageIndex, null, sortName, isAsc, null);
        params.put("beginTime", beginTime);
        params.put("endTime", endTime);
        params.put("q", q);
        params.put("refCustomerId",customerId);
        //留言状态
        if (status == CsrConstants.AskBoardStatus.UNSOLVED) {

            params.put("status", null);
        } else if (status == CsrConstants.AskBoardStatus.SOLUTION ) {

            params.put("status", true);
        } else if (status == CsrConstants.AskBoardStatus.UNKNOWN) {

            params.put("status", false);
        }

        if (customerId == 0) {

            params.put("anonymity", customerName);
        }

        if (PrincipalUtils.getDomainId() == AppDomain.CUSTOMER) {

            params.put("refCustomerId", PrincipalUtils.getAccountId());
        }

        ParamData pd = this.convertQueryParams(params);
        List<CsrAskBoardSchema> csrAskBoardSchemaList = dao.findForList(getSqlName("findByParamListPage"), pd, CsrAskBoardSchema.class);

        if (csrAskBoardSchemaList != null
                && csrAskBoardSchemaList.size() > 0) {

            for (int i = 0; i < csrAskBoardSchemaList.size(); i++) {

                CsrAskBoardSchemaDto csrAskBoardSchemaDto = new CsrAskBoardSchemaDto();

                BeanUtils.copyProperties(csrAskBoardSchemaList.get(i), csrAskBoardSchemaDto);

                if (csrAskBoardSchemaList.get(i).getRefCustomerId() == 0) {

                    CsrAskBoardSchema csrAskBoardSchema = findById(csrAskBoardSchemaList.get(i).getId());

                    if (csrAskBoardSchema != null) {

                        csrAskBoardSchemaDto.setCustomerFullName(csrAskBoardSchema.getAnonymity());
                        csrAskBoardSchemaDto.setCustomerUserName(csrAskBoardSchema.getAnonymity());
                    }
                } else {

                    CusUser cusUser = customerUserService.findById(csrAskBoardSchemaList.get(i).getRefCustomerId());

                    if (cusUser != null) {

                        csrAskBoardSchemaDto.setCustomerFullName(cusUser.getFullName());
                        csrAskBoardSchemaDto.setCustomerUserName(cusUser.getUserName());
                    }
                }



                if (csrAskBoardSchemaDto.getModeratorForReplyer()) {

                    CusUser cusUser1 = customerUserService.findById(csrAskBoardSchemaDto.getLastReplyId());

                    if (cusUser1 != null) {

                        csrAskBoardSchemaDto.setLastReplyerFullName(cusUser1.getFullName());
                        csrAskBoardSchemaDto.setLastReplyerUserName(cusUser1.getUserName());
                    }
                } else {

                    UserDto userDto = userService.findUserDetailByUserId(csrAskBoardSchemaDto.getLastReplyId());

                    if (userDto != null) {

                        csrAskBoardSchemaDto.setLastReplyerUserName(userDto.getUserName());
                        csrAskBoardSchemaDto.setLastReplyerFullName(userDto.getFullName());
                    }
                }

                csrAskBoardSchemaDtoList.add(csrAskBoardSchemaDto);

            }
        }

        QResultDto qResultDto = new QResultDto();

        qResultDto.setData(csrAskBoardSchemaDtoList);
        qResultDto.setPagination(pd.getPagination());

        return qResultDto;
    }

    @Override
    public void update(CsrAskBoardSchema csrAskBoardSchema) {

        if (csrAskBoardSchema != null) {

            dao.update(getSqlName("updateById"), csrAskBoardSchema);
        }
    }

    @Override
    public void doneCsrAskBoardById(int id) {

        CsrAskBoardSchema csrAskBoardSchema = new CsrAskBoardSchema();

        csrAskBoardSchema.setId(id);
        csrAskBoardSchema.setStatus(true);

        update(csrAskBoardSchema);
    }

    @Override
    public CsrAskBoardSchema findById(Integer id) {

        CsrAskBoardSchema csrAskBoardSchema = null;

        if (id != null && id > 0) {

            csrAskBoardSchema = (CsrAskBoardSchema) dao.findForObject(getSqlName("selectByPrimaryKey"), id);
        }

        return csrAskBoardSchema;
    }

    @Override
    public Map<String,String> generateSerialNumber() {

        Map<String,String> resMap = new HashedMap();

        Integer maxSerialNumber = (Integer) dao.findForObject(getSqlName("getMaxSerialNumber"),null);

        if (maxSerialNumber == null) {

            maxSerialNumber = 0;
        }

        maxSerialNumber = maxSerialNumber + 1;

        String serialNumber = String.format("%05d",maxSerialNumber);

        resMap.put("serialNumber", serialNumber);

        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyMMdd");
        String dateString = formatter.format(currentTime);

        resMap.put("dateString",dateString);

        return resMap;
    }

    @Override
    public QResultDto getCodeList(String q, int pageIndex, int pageSize, String sortName, boolean isAsc, String language) {
        ParamData pd = this.convertQueryParams(new QueryParams(pageSize, pageIndex, q, sortName, isAsc, language));

        List<CsrAskBoardSchemaDto> csrAskBoardSchemaDtoList = dao.findForList(getSqlName("getCodeListPage"), pd, CsrAskBoardSchemaDto.class);


        QResultDto qResultDto = new QResultDto();
        qResultDto.setData(csrAskBoardSchemaDtoList);
        qResultDto.setPagination(pd.getPagination());

        return qResultDto;
    }

    @Override
    public CsrAskBoardSchemaDto checkCodeExist(String code) {

        CsrAskBoardSchemaDto csrAskBoardSchemaDto = null;

        if (code != null && !"".equals(code)) {

            csrAskBoardSchemaDto = (CsrAskBoardSchemaDto)dao.findForObject(getSqlName("selectByCode"), code);

            if (csrAskBoardSchemaDto != null) {

                if (csrAskBoardSchemaDto.getRefCustomerId() != null
                        && csrAskBoardSchemaDto.getRefCustomerId() > 0) {

                    CusUser cusUser = customerUserService.findById(csrAskBoardSchemaDto.getRefCustomerId());

                    if (cusUser != null) {

                        csrAskBoardSchemaDto.setCustomerUserName(cusUser.getUserName());
                        csrAskBoardSchemaDto.setCustomerFullName(cusUser.getFullName());
                        csrAskBoardSchemaDto.setCustomerTelNo(cusUser.getMobilePhone());
                    }
                }
            }
        }

        return csrAskBoardSchemaDto;
    }

    @Override
    public Map saveForLogin(CsrAskBoardSchema entry) {

        int resId = 0;

        if (entry != null) {

            entry.setRefCustomerId(PrincipalUtils.getAccountId());

            entry.setLastReplyId(PrincipalUtils.getAccountId());

            entry.setModeratorForReplyer(true);

            entry.setStatus(false);

            Map<String,String> serialNumber = generateSerialNumber();

            entry.setCode(serialNumber.get("dateString")+serialNumber.get("serialNumber"));

            entry.setSerialNumber(Integer.valueOf(serialNumber.get("serialNumber")));

            dao.save(getSqlName("insertSelective"), entry);

            //保存操作日志
            Map<String, Object> dataBackup = new HashMap<>();
            dataBackup.put("ADD_CUSTOMERSERVICE_ASKBOARD_SCHEMA", entry);
            PrincipalLogUtils.addOperationLog(ModuleNames.CSR, ModuleNames.CSR_ASK_BOARD, UserActions.ADD, "新增客服问题单", dataBackup);

            resId = entry.getId();
        }

        CsrAskBoardSchema csrAskBoardSchema = (CsrAskBoardSchema)dao.findForObject(getSqlName("selectByPrimaryKey"),resId);

        Map<String,Object> map = new HashedMap();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        if (csrAskBoardSchema != null) {

            map.put("id",resId);
            map.put("createTime",sdf.format(csrAskBoardSchema.getCreateTime()));
        }


        return map;
    }

    @Override
    public int getUnReadCount(Integer refCustomerId) {

        int unReadMessageCount = 0;

        Map<String, Object> map = new HashedMap();

        map.put("refCustomerId", refCustomerId);

        List<CsrAskBoardSchema> csrAskBoardSchemaList = dao.findForList(getSqlName("getUnReadMessage"),map,CsrAskBoardSchema.class);

        if (csrAskBoardSchemaList != null && csrAskBoardSchemaList.size() > 0) {

            unReadMessageCount = csrAskBoardSchemaList.size();
        }

        return unReadMessageCount;
    }

    @Override
    public void flagForRead(List<Integer> ids) {

        if (ids != null && ids.size() > 0) {

            dao.update(getSqlName("flagForRead"),ids);
        }
    }

    private void checkDataValid(CsrAskBoardSchema csrAskBoardSchema) {

        if (StringUtils.isEmpty(csrAskBoardSchema.getTopic())) {

            throw Exceptions.bizException(ErrorCodes.ERROR_ARGUMENT_EMPTY, "topic");
        }
    }

    @Override
    protected String getMapperNamespace() {
        return "CsrAskBoardSchemaMapper";
    }
}
